﻿using System;
using System.Collections.Generic;
using System.Web;

namespace JQueryRotate
{
    /// <summary>
    /// RandRotate 的摘要说明
    /// </summary>
    public class RandRotate : IHttpHandler
    {
        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";

            List<Sector> sectorList = XmlHelper.GetSectorList();

            Dictionary<int, Sector> sectorDic = new Dictionary<int, Sector>();
            List<int> sectorIndexList = new List<int>();
            foreach (Sector s in sectorList)
            {
                if (s.TimesAvailable < 0 || s.TimesRecord < s.TimesAvailable) { 
                    sectorDic.Add(s.Index, s);
                    sectorIndexList.Add(s.Index);
                }

            }

            Random ro = new Random();
            int iResult;
            int iUp = sectorIndexList.Count;
            iResult = ro.Next(0, iUp);
            int key = sectorIndexList.ToArray()[iResult];

            Sector sectorGot = sectorDic[key];
            ResponseModel responseModel = new ResponseModel(Convert.ToInt32(sectorGot.Angle), sectorGot.Text);
            XmlHelper.GotOneTime(sectorGot.Index);

            context.Response.Write(Newtonsoft.Json.JsonConvert.SerializeObject(responseModel));
        }
    }

    public class Sector
    {
        public int Index { get; set; }

        public double Angle { get; set; }

        public string Text { get; set; }

        public int TimesAvailable { get; set; }

        public int TimesRecord { get; set; }

        public Sector(int index, double angle, string text, int timesAvailable,int timesRecored)
        {
            this.Index = index;
            this.Angle = angle;
            this.Text = text;
            this.TimesAvailable = timesAvailable;
            this.TimesRecord = timesRecored;
        }
    }
    public class ResponseModel
    {
        /// <summary>
        /// 角度
        /// </summary>
        public int Angle { get; set; }
        /// <summary>
        /// 消息
        /// </summary>
        public string Message { get; set; }

        public ResponseModel() { }

        public ResponseModel(int angle, string message)
        {
            this.Angle = angle;
            this.Message = message;
        }
    }
}